//
//  JVerdorController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/14.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JVerdorController.h"
#import "JShopCarViewController.h"
#import "JSearchProductController.h" // 搜索页面
#import "JVerdorHeadView.h"
#import "UICollectionView+JCollectionView.h"
#import "JBaseCollectionViewCell.h"
#import "JProductDetailController.h"

#import "JDropDownListView.h" // 商品类型 View

#import "JContactVerdorController.h" // 联系商家
#import "JFeedbackController.h"
#define bottomBtnTag 50
#define headViewHeight 290

@interface JVerdorController ()<UISearchBarDelegate , UICollectionViewDelegate , UICollectionViewDataSource>

@property (nonatomic ,strong) NSIndexPath *indexPath;
@property (nonatomic, assign) NSInteger CollectCount;
@property (nonatomic, assign) BOOL isCollectVerdor;
@property (nonatomic, strong) JVerdorHeadView *headView;
@property (nonatomic, strong) JDropDownListView *listView;

@property (nonatomic, strong) JVerdorDetailModel *verdorModel;
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic , strong) JGetPageModel *pageModel;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, copy) NSArray *typeDataArr;

@end

@implementation JVerdorController

- (NSArray *)typeDataArr
{
    if (!_typeDataArr) {
        _typeDataArr = [NSArray array];
    }
    return _typeDataArr;
}

- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (JGetPageModel *)pageModel
{
    if (!_pageModel) {
        _pageModel = [JGetPageModel new];
        _pageModel.orderBy = 0;
        _pageModel.pageIndex = 1;
        _pageModel.pageSize = 10;
        
    }
    return _pageModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    
    // 加载店铺详情
    [self loadVerdorInfoRequest];
    // 产品分类
    [self loadVerdorTypeDataRequest];
    // 导航栏
    [self setUpNav];
    // 瀑布流
    [self setConfigCollectView];
    // 底部按钮
    [self setConfigbottomView];
    // 按类型加载商品
    [self loadVerdorProductRequest:self.pageModel];
}

// 配置导航栏
- (void)setUpNav
{
    self.titleLabel.hidden = YES;
    self.leftButton.hidden = NO;
    self.rightButton.hidden = NO;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    [self.rightButton setImage:[UIImage imageNamed:@"shopcarsmall"] forState:UIControlStateNormal];
    
    CGRect searchRect = CGRectMake(CGRectGetMaxX(self.leftButton.frame) + 5, 25, CGRectGetMinX(self.rightButton.frame) - 10 - CGRectGetMaxX(self.leftButton.frame), 32);
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:searchRect];
    searchBar.delegate = self;
    searchBar.backgroundColor = [UIColor clearColor];
    
    
    searchBar.placeholder = @"宝贝搜索";
    
    for (UIView *subViews in searchBar.subviews) {
        if ([subViews isKindOfClass:[UIView class]]) {
            [[subViews.subviews objectAtIndex:0] removeFromSuperview];
            
            if ([[subViews.subviews objectAtIndex:0] isKindOfClass:[UITextField class]]) {
                UITextField *textF = [subViews.subviews objectAtIndex:0];
                textF.font = kFONT_TITLE(12);
                textF.backgroundColor = kRGBColor(240, 240, 240);
                
                UIColor *color = [UIColor grayColor];
                NSAttributedString *attri = [[NSAttributedString alloc]initWithString:@"宝贝搜索" attributes:@{NSForegroundColorAttributeName:color}];
                
                [textF setAttributedPlaceholder:attri];
            }
        }
    }
    
    [self.navigationView addSubview:searchBar];
    
}

- (void)setConfigCollectView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    _collectView = [UICollectionView initWithCollectionView:CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame) - 50) withDelegate:self];
    
    _collectView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageModel.pageIndex += 1;
        [self loadVerdorProductRequest:self.pageModel];
        [_collectView.mj_footer endRefreshing];
    }];
    
    [_collectView.mj_footer beginRefreshing];
    
    [self.collectView registerClass:[JVerdorHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JVerdorHeadView class])];
    
    // 注册cell
    [self.collectView registerClass:[JBaseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class])];
    
    [self.contentView addSubview:_collectView];
    
}

- (void)setConfigbottomView {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.contentView.frame) - 50, kWindowW, 50)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bottomView];
    
    CGFloat btnWidth = kWindowW/3.0;
    NSArray *nameArr = @[@"投诉",@"商品分类",@"联系客服"];
    for (int i = 0; i < 3 ; i++) {
        UIButton *collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        collectBtn.frame = CGRectMake(btnWidth * i , 0, btnWidth, 50);
        collectBtn.titleLabel.font = kFONT_TITLE(14);
        
        collectBtn.tag = bottomBtnTag+ i;
        
        [collectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:collectBtn];
        
        if (i == 1) {
            collectBtn.selected = NO;
            [collectBtn setTitle:[NSString stringWithFormat:@" %@",nameArr[i]] forState:UIControlStateNormal];
            [collectBtn setImage:[UIImage imageNamed:@"morewhite"] forState:UIControlStateNormal];
        }
        else
        {
            [collectBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        }
        [collectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
    CALayer *line3 = [CALayer layer];
    line3.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line3.frame = CGRectMake(0,0 , kWindowW, 0.5);
    [bottomView.layer addSublayer:line3];
    
    CALayer *line = [CALayer layer];
    line.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line.frame = CGRectMake(btnWidth, 8 , 1, 34);
    [bottomView.layer addSublayer:line];
    
    CALayer *line2 = [CALayer layer];
    line2.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    line2.frame = CGRectMake(btnWidth * 2, 8 , 1, 34);
    [bottomView.layer addSublayer:line2];
    
    
    _listView = [[JDropDownListView alloc]initWithFrame:CGRectMake(0, 0, self.collectView.width, self.view.height - 50)];
    _listView.hidden = YES;
    [self.view addSubview:_listView];
    [self.view bringSubviewToFront:_listView];
    
    __weak typeof(self) weakSelf = self;
    _listView.cancelBlock = ^{
        [weakSelf ProductTypeViewAnimation:NO];
        UIButton *btn = [bottomView viewWithTag:bottomBtnTag+1];
        btn.selected = NO;
    };
    
    _listView.productTypeBlock = ^(JVerdorProductTypeModel *typeModel) {
        
        [weakSelf ProductTypeViewAnimation:NO];
        UIButton *btn = [bottomView viewWithTag:bottomBtnTag+1];
        btn.selected = NO;
        
        JSearchProductController *searchVC = [[JSearchProductController alloc]init];
        searchVC.VendorId = weakSelf.verdorID;
        searchVC.CategoryId = typeModel.Id;
        [weakSelf.navigationController pushViewController:searchVC animated:YES];
        
    };
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JBaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([JBaseCollectionViewCell class]) forIndexPath:indexPath];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        cell.prodeutModel = _dataArr[indexPath.row];
    });
    
    return cell;
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        self.indexPath = indexPath;
        JVerdorHeadView *headerView = [_collectView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([JVerdorHeadView class]) forIndexPath:indexPath];
        headerView.verdorModel = self.verdorModel;
        headerView.isCollect = self.isCollectVerdor;
        headerView.collectCountInt = self.CollectCount;
        headerView.verdorBtnBlock = ^(NSInteger tag, JVerdorDetailModel *model, NSInteger isDown) {
            if (tag == 10) {
                JContactVerdorController *vc = [[JContactVerdorController alloc]init];
                vc.conID = [NSString stringWithFormat:@"%ld",model.VendorOwnerId];
                vc.usID = [NSString stringWithFormat:@"%ld",[GLOBALDATA userInfoModel].CustomerId];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if (tag == 11)
            {
                // 收藏店铺
                [self collectVerdorBtnClick];
            }
            else {
                //isDown   0 表示不是价格 1 价格下 2 价格上
                [self loadVerdorProductTypeRequest:tag - 20 isDown:isDown];
                
            }
        };
        return headerView;
    }
    
    return nil;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellwidth = (kWindowW - 15*3)/2.0;
    return (CGSize){cellwidth,260};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15, 15, 15, 15);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}

// headView set height
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
    return (CGSize){kWindowW, headViewHeight};
}

#pragma mark ---- UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    JProductDetailController *detail = [[JProductDetailController alloc]init];
    detail.productModel = _dataArr[indexPath.row];
    detail.inputType = 1; // 表示非购物车进入商品详情
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark - searchBar
// searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"===%@", searchBar.text);
    // 调用filterBySubstring:方法执行搜索
//    [self filterBySubstring:searchBar.text];
    // 放弃作为第一个响应者，关闭键盘
    [searchBar resignFirstResponder];
    
    JSearchProductController *searchVC = [[JSearchProductController alloc]init];
    searchVC.searchText = searchBar.text;
    searchVC.VendorId = self.verdorID;
    [self.navigationController pushViewController:searchVC animated:YES];
}

//- (void) filterBySubstring:(NSString*) subStr
//{
//    NSLog(@"----filterBySubstring------");
//    // 设置为搜索状态
//    //    isSearch = YES;
//    // 定义搜索谓词
//    NSPredicate* pred = [NSPredicate predicateWithFormat:
//                         @"SELF CONTAINS[c] %@" , subStr];
//    // 使用谓词过滤NSArray
//    //    searchData = [tableData filteredArrayUsingPredicate:pred];
//    // 让表格控件重新加载数据
//    //    [tableView reloadData];
//}

// 收藏店铺 功能
- (void)collectVerdorBtnClick {
    NSString *url = @"Vendor/CollectVendor";
    [JNetManager getCollectVendorRequedtUrl:url
                                   verdorId:self.verdorID
                                    success:^(id response) {
                                        if (response) {
                                            
                                            if (self.verdorModel.IsCollected == 1) {
                                                self.verdorModel.IsCollected = 0;
                                                self.isCollectVerdor = NO;
                                            }
                                            else
                                            {
                                                self.verdorModel.IsCollected = 1;
                                                self.isCollectVerdor = YES;
                                            }
                                            self.CollectCount = [response integerValue];
                                            [_collectView reloadData];
                                            
                                        }
                                    } failure:^(NSString *err) {
                                        [SVProgressHUD showErrorWithStatus:err];
                                    }];
}

//isDown   0 表示不是价格 1 价格下 2 价格上
- (void)loadVerdorProductTypeRequest:(NSInteger)selType   isDown:(NSInteger)isDown
{
    switch (selType) {
        case 0:
        {
            self.pageModel.orderBy = 0;
        }
            break;
        case 1:
        {
            self.pageModel.orderBy = 3;
        }
            break;
        case 2:
        {
            self.pageModel.orderBy = 1;
        }
            break;
        case 3:
        {
            if (isDown == 1) {
                self.pageModel.orderBy = 2;
            }
            else
            {
                self.pageModel.orderBy = 4;
            }
            
        }
            break;
            
        default:
            break;
    }
    [self.dataArr removeAllObjects];
    self.pageModel.pageIndex = 1;
    [self loadVerdorProductRequest:self.pageModel];
}

// 获取商品 请求
- (void)loadVerdorProductRequest:(JGetPageModel *)model
{
    [SVProgressHUD show];
    NSString *url = @"Products/GetProducts";
    [JNetManager GetVerdorProductsRequedtUrl:url
                                    verdorId:self.verdorID
                                   pagemodel:self.pageModel
                                     success:^(id response) {
                                         [SVProgressHUD dismiss];
                                         if (response) {
                                             
                                             NSMutableArray *daraMArr = response;
                                             [self.dataArr addObjectsFromArray:daraMArr];
                                             
                                             [_collectView reloadData];
                                         }
                                     } failure:^(NSString *err) {
                                         [SVProgressHUD dismiss];
                                         [SVProgressHUD showErrorWithStatus:err];
                                     }];
}

// 加载店铺商品类型数据
- (void)loadVerdorTypeDataRequest
{
    NSString *url = @"Categories/GetCategoriesByVendorId";
    [JNetManager GetCategoriesByVendorIdRequedtUrl:url
                                          verdorId:self.verdorID
                                           success:^(id response) {
                                               if (response) {
                                                   self.typeDataArr = response;
                                                   _listView.dataArr = self.typeDataArr;
                                               }
                                           } failure:^(NSString *err) {
                                               [SVProgressHUD showErrorWithStatus:err];
                                           }];
}

// 加载店铺详情
- (void)loadVerdorInfoRequest
{
    NSString *url = @"Vendor/GetVendorById";
    [JNetManager getGetVendorByIdRequedtUrl:url
                                   verdorId:self.verdorID
                                    success:^(id response) {
                                        if (response) {
                                            self.verdorModel = response;
                                            if (self.verdorModel.IsCollected == 1) {
                                                _isCollectVerdor = YES;
                                            }
                                            else
                                            {
                                                _isCollectVerdor = NO;
                                            }
                                            
                                            self.CollectCount = [self.verdorModel.CollectCount integerValue];
                                            [_collectView reloadData];
                                            
                                        }
                                        
                                    } failure:^(NSString *err) {
                                        [SVProgressHUD showErrorWithStatus:err];
                                    }];
}

- (void)btnClick:(UIButton *)btn
{
    if (btn.tag == bottomBtnTag) {
//        NSLog(@"投诉");
        JFeedbackController *userInfoVC = [[JFeedbackController alloc]init];
        userInfoVC.inputType = 1;
        userInfoVC.shopID = self.verdorID;
        [self.navigationController pushViewController:userInfoVC animated:YES];
    }
    if (btn.tag == bottomBtnTag + 1) {
//        NSLog(@"商品分类");
        
        btn.selected = !btn.selected;
        [self ProductTypeViewAnimation:btn.selected];
        
    }
    if (btn.tag == bottomBtnTag + 2) {
//        NSLog(@"联系商家");
        JContactVerdorController *vc = [[JContactVerdorController alloc]init];
        vc.conID = [NSString stringWithFormat:@"%ld",_verdorModel.VendorOwnerId];
        vc.usID = [NSString stringWithFormat:@"%ld",[GLOBALDATA userInfoModel].CustomerId];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (void)ProductTypeViewAnimation:(BOOL)isShow
{
    
    CGFloat viewHeight = CGRectGetHeight(self.view.frame) - 50;
    
    if (isShow) {
        _listView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            
            if (self.typeDataArr.count > 0) {
                CGFloat tableViewHeight = self.typeDataArr.count * 44;
                
                if (tableViewHeight <= 0.6 * viewHeight) {
                    _listView.tableView.frame = CGRectMake(self.contentView.width / 3.0, viewHeight - tableViewHeight, self.contentView.width / 3.0, tableViewHeight);
                }
                else
                {
                    _listView.tableView.frame = CGRectMake(self.contentView.width / 3.0, viewHeight - (0.6 * viewHeight), self.contentView.width / 3.0, 0.6 * viewHeight);
                }
                
            }
        }];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            
            _listView.tableView.frame = CGRectMake(self.contentView.width / 3.0, viewHeight , 0, 0);
            
            [self typeViewCancel];
            // 延迟消失
            //            [self performSelector:@selector(typeViewCancel) withObject:nil afterDelay:0.3];
        }];
    }
}

// 隐藏商品类型列表
- (void)typeViewCancel
{
    _listView.hidden = YES;
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(UIButton *)rightButton
{
    // 前往购物车
    JGoShopCarViewController;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
